import React, {PureComponent} from "react"
import "./index.less"
import infoCompose, {titleCreate, sizeColumn, ViewType} from "./compose"

import {
  ArrowLeftOutlined,
  CloudDownloadOutlined,
  LeftOutlined,
  LikeOutlined,
  RightOutlined,
} from '@ant-design/icons';

import { Icon as LegacyIcon } from '@ant-design/compatible';
import { Breadcrumb, Button, Carousel, Radio, PageHeader, Table, Empty, Checkbox } from "antd";
import {Link} from "react-router-dom";
import {withRouter} from "react-router"
import {HOST, SERVER_HOST, defaultSize} from "../../../../shared/project-config"
import cs from "classnames"
import "animate.css"
import {seasonRenders} from "../../render"
import PictureSVG from "../../../../images/svg/pictures.svg"
import {read} from "zr-react-toolbox"
import ThreeStage from "libs/three"
import FileItem from "./item"


const itemMaxSize = 5
const settings = {
  dots: true,
  infinite: true,
  speed: 500,
  slidesToShow: itemMaxSize,
  slidesToScroll: itemMaxSize,
  variableWidth: true,
  initialSlide: 0,
}

const size = defaultSize

const canToRight = (itemNum, naviIndex, imageNum) => naviIndex * itemMaxSize + itemMaxSize >= imageNum

const priceCalc = (file, data) => {
  if (!file) return '0.00'
  if (file.download === true) {
    return '已购买'
  }
  if (file.type === 'BOKE') {
    return (data.cadPrice / 100).toFixed(2)
  }
  if (file.type === 'PLT') {
    return (data.pltPrice / 100).toFixed(2)
  }
  return '0.00'
}

const modeWidth = 300
const modeHeight = 600

@withRouter
@infoCompose
export default class BuyInfo extends PureComponent {

  constructor(props) {
    super(props);
    this.ref = undefined
  }

  onRefs = (ref) => this.ref = ref

  onNext = (event) => {
    event.stopPropagation()
    const images = read(this.props, 'data.pictureFiles')
    const len = images.length < itemMaxSize ? images.length : itemMaxSize
    const {naviIndex, $naviIndex} = this.props
    if (canToRight(len, naviIndex, images.length)) {
      return
    }
    if (this.ref) {
      this.ref.next()
      $naviIndex(naviIndex + 1)
    }
  }

  onPrev = (event) => {
    event.stopPropagation()
    const {naviIndex, $naviIndex} = this.props
    if (naviIndex <= 0) {
      return
    }
    if (this.ref) {
      $naviIndex(naviIndex - 1)
      this.ref.prev()
    }
  }

  render() {
    const {
      data, picture, onThumbSelect, onBack, naviIndex, sizeData,
      toDownload, addFavorite, onViewTypeChange, viewType, onMakeRequest, readOnly, preUrlName,
      checkedFiles, onFileCheck, toBatchDownload, orderFeeCalc
    } = this.props
    const {pictureFiles, categories, seasons, sizeFiles} = data
    const images = pictureFiles || []
    settings.slidesToShow = images.length < itemMaxSize ? images.length : itemMaxSize
    const rightDisable = canToRight(settings.slidesToShow, naviIndex, images.length);


    const pltSizeFiles = (sizeFiles || []).filter(i => i.type === 'PLT')
    const cadSizeFiles = (sizeFiles || []).filter(i => i.type === 'BOKE' || i.type === 'CAD')

    const types = (categories || []).filter(c => c.type === 'type')
    const purposes = (categories || []).filter(c => c.type === 'purpose')
    const styles = (categories || []).filter(c => c.type === 'style')
    const peoples = (categories || []).filter(c => c.type === 'people')

    //文件是否被勾选
    const isCheck = (f) => checkedFiles.some(i => i.id === f.id)
    const canDownloadPack = checkedFiles && checkedFiles.length > 0
    const totalDownloadFee = orderFeeCalc(checkedFiles)

    return (
      <div className={'zr-panel'}>

        <div className={'zr-panel-header'}>
          <div>
            {/*<Breadcrumb>*/}
            {/*  <Breadcrumb.Item><Link to="/app/home">首页</Link></Breadcrumb.Item>*/}
            {/*  <Breadcrumb.Item><Link to="/app/library">{preUrlName || '版型库'}</Link></Breadcrumb.Item>*/}
            {/*  <Breadcrumb.Item>版型详细</Breadcrumb.Item>*/}
            {/*</Breadcrumb>*/}
            <PageHeader backIcon={<ArrowLeftOutlined />}
                        onBack={onBack} title={`版型详细`}
                        subTitle={`版型详细 - ${data.code}`}/>
          </div>
        </div>

        <div className={'ld2-info-page-box'}>

          <section>
            <div className={'ld2-info-view'} style={{minWidth: `${modeWidth + 50}px`}}>
              <Radio.Group defaultValue={ViewType.picture} buttonStyle="solid" onChange={onViewTypeChange}>
                <Radio.Button value={ViewType.picture}>平面图片</Radio.Button>
                <Radio.Button value={ViewType.threeDimensional}>三维模型</Radio.Button>
                <Radio.Button value={ViewType.video}>试穿视频</Radio.Button>
              </Radio.Group>

              {
                viewType === ViewType.picture ?
                  <div className={'info-image'}>
                    <div className={cs('info-image-border', {'no-image': !picture})}>
                      <img className={'animated fadeIn'} src={picture ? `${HOST}/file/image/${picture}` : PictureSVG}/>
                    </div>
                    <div className={'image-navigator'}>
                      <div className={cs('image-navigator-left', {'disable': naviIndex <= 0})}>
                        <LeftOutlined onClick={this.onPrev} />
                      </div>
                      <Carousel ref={this.onRefs} className={'info-image-navigation-carousel'} {...settings}>
                        {
                          images.map(i => (
                            <div key={i.id}
                                 className={cs('navigator-image-border', {'border-selected': i.id === picture})}>
                              <div>
                                <img src={`${HOST}/file/thumb/${i.id}`} onClick={onThumbSelect(i)}/>
                              </div>
                            </div>)
                          )}
                      </Carousel>
                      <div className={cs('image-navigator-right', {'disable': rightDisable})}>
                        <RightOutlined onClick={this.onNext} />
                      </div>
                    </div>
                  </div>
                  : undefined
              }

              {
                viewType === ViewType.threeDimensional ?
                  <ThreeStage
                    basePath={`${SERVER_HOST}/three/`}
                    mtlName={'male02_dds.mtl'}
                    objUrl={`${SERVER_HOST}/three/male02.obj`}
                    width={modeWidth}
                    height={modeHeight}></ThreeStage>
                  : undefined
              }

              {
                viewType === ViewType.video ?
                  <div className={'video-container'}>
                    <h3>即将上线,敬请期待</h3>
                    <p/>
                  </div>
                  : undefined
              }

            </div>

            <div className={'info-properties'}>
              <h1>
                {titleCreate(data)}
              </h1>
              {
                readOnly ? undefined :
                  <div>
                    {data.description || '暂无描述'}
                  </div>
              }
              <table>
                <tr>
                  <td width="100px"><label>平台编码</label></td>
                  <td>{data.sysCode}</td>
                </tr>
                <tr>
                  <td><label>服装编码</label></td>
                  <td>{data.code}</td>
                </tr>
                <tr>
                  <td><label>服装类别</label></td>
                  <td>{data['sizeTypeName']}</td>
                </tr>
                <tr>
                  <td><label>适应季节</label></td>
                  <td>
                    <div>
                      {
                        !seasons || seasons.length < 1
                          ? '暂无'
                          : seasons.map(s => seasonRenders[s]).join('、')
                      }
                    </div>
                  </td>
                </tr>
                <tr>
                  <td><label>服装分类</label></td>
                  <td>
                    {
                      !types || types.length < 1
                        ? '暂无'
                        : types.map(c => c.name).join('、')
                    }
                  </td>
                </tr>
                <tr>
                  <td><label>服装风格</label></td>
                  <td>
                    {
                      !styles || styles.length < 1
                        ? '暂无'
                        : styles.map(c => c.name).join('、')
                    }
                  </td>
                </tr>
                <tr>
                  <td><label>适用人群</label></td>
                  <td span={16}>

                    {
                      !peoples || peoples.length < 1

                        ? '暂无'
                        : peoples.map(c => c.name).join('、')
                    }
                  </td>
                </tr>
                <tr>
                  <td><label>适用场合</label></td>
                  <td span={16}>
                    {
                      !purposes || purposes < 1
                        ? '暂无'
                        : purposes.map(c => c.name).join('、')
                    }
                  </td>
                </tr>

                {
                  !readOnly ? undefined :
                    <tr>
                      <td><label>详细描述</label></td>
                      <td>
                        <div style={{maxWidth: '380px'}}>
                          {data.description + data.description || '暂无'}
                        </div>
                      </td>
                    </tr>
                }

                <tr>
                  <td colSpan={2}>
                    <label className={'file-item-title'}>博克CAD文件
                      {readOnly ? undefined : <span>包含所有尺码、可自由修改</span>}
                    </label>
                  </td>
                </tr>
                <tr>
                  <td colSpan="2" className={'files-td'}>
                    {
                      cadSizeFiles && cadSizeFiles.length > 0 ?
                        (cadSizeFiles || []).map(
                          f => {
                            return <FileItem type={'BOKE'}
                                             data={data}
                                             price={data.cadPrice}
                                             file={f}
                                             isCheck={isCheck}
                                             onFileCheck={onFileCheck}
                                             readOnly={readOnly}
                                             toDownload={toDownload}/>
                          }) : <Empty description={'暂无智能版型文件'} image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
                    }
                  </td>
                </tr>

                <tr>
                  <td colSpan={2}>
                    <label className={'file-item-title'}>PLT文件
                      {readOnly ? undefined : <span>固定尺码、不可编辑、可直接打印</span>}
                    </label>
                  </td>
                </tr>
                <tr>
                  <td colSpan={2} className={'files-td'}>
                    {
                      pltSizeFiles && pltSizeFiles.length > 0
                        ? (pltSizeFiles || []).map(
                        f => {
                          return <FileItem type={'PLT'}
                                           file={f}
                                           data={data}
                                           price={data.pltPrice}
                                           isCheck={isCheck}
                                           onFileCheck={onFileCheck}
                                           readOnly={readOnly}
                                           toDownload={toDownload}/>
                        })
                        : <Empty description={'暂无版型文件'} image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
                    }
                  </td>
                </tr>

                {
                  readOnly ? undefined :
                    <tr>
                      <td colSpan="2" className={'buttons-td'}>
                        <div>
                          <Button size={size} type={'primary'} className={'green'} onClick={addFavorite}
                                  disabled={data.favorite}>
                            {data.favorite ? '已收藏' : <span><LegacyIcon type={'heart'}/> 收藏</span>}
                          </Button>

                          {
                            sizeFiles && sizeFiles.length > 0
                              ?
                              (canDownloadPack ?
                                  <div>
                                    <Button size={size} type={'primary'}
                                            onClick={toBatchDownload(checkedFiles)}>
                                      <CloudDownloadOutlined /> 打包下载 [{checkedFiles.length}]
                                    </Button>
                                    <b className={'total-fee'}>共:{totalDownloadFee}</b>
                                  </div> : undefined
                              )
                              : <Button size={size} type={'primary'} onClick={onMakeRequest}>
                                <LikeOutlined /> 申请制版
                              </Button>
                          }
                        </div>
                      </td>
                    </tr>
                }
              </table>
            </div>
          </section>

          <div className={'size-table-container'}>
            <h1>可选尺码</h1>
            <div>当前版型可选择的定制参数</div>
            <Table
              className={'clothing-info-size-table'}
              bordered={true}
              columns={sizeColumn(sizeData['sizeTableParam'])}
              dataSource={sizeData['sizeTables']} size="middle"
              pagination={false}
            />
          </div>
        </div>
      </div>
    );
  }
}